use std::path::PathBuf;
use tracing::{Level, Subscriber};
use tracing_appender::rolling::daily;
use tracing_subscriber::fmt::writer::MakeWriterExt;
use tracing_subscriber::{
    EnvFilter, Registry, fmt, fmt::time::OffsetTime, layer::SubscriberExt, util::SubscriberInitExt,
};

pub fn init_log(log_dir: &PathBuf) {
    // 配置时间格式
    let time_fmt = time::format_description::parse(
        "[year]-[month]-[day] [hour]:[minute]:[second].[subsecond digits:3]",
    )
    .expect("Failed to parse time format");
    let time_offset = time::UtcOffset::current_local_offset().unwrap_or(time::UtcOffset::UTC);
    let timer = OffsetTime::new(time_offset, time_fmt);

    // 文件输出 - 无ANSI颜色
    let file_appender = daily(log_dir, "err.log")
        .with_max_level(Level::WARN)
        .or_else(daily(log_dir, "out.log"));

    let file_layer = fmt::layer()
        .with_writer(file_appender)
        .with_ansi(false) // 文件输出禁用ANSI颜色
        .with_timer(timer.clone())
        .with_target(true);

    // 控制台输出 - 有ANSI颜色
    let std_appender = std::io::stderr
        .with_max_level(Level::WARN)
        .or_else(std::io::stdout);

    let console_layer = fmt::layer()
        .with_writer(std_appender)
        .with_ansi(true) // 控制台输出启用ANSI颜色
        .with_timer(timer)
        .with_target(true);

    // 组合两层日志配置并初始化
    tracing_subscriber::registry()
        .with(EnvFilter::from_default_env())
        .with(file_layer)
        .with(console_layer)
        .init()
}
